package Config;

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.core.io.Resource;

import javax.sql.DataSource;




@PropertySource("classpath:jdbc.properties")
@MapperScan("com.tedu.mapper")
public class MybatisConfig {

    @Autowired
    Environment env;

    /**
     * 配置数据库连接池
     * @return
     */
    @Bean
    public DataSource dataSource(){
        DruidDataSource ds = new DruidDataSource();

        ds.setDriverClassName(env.getProperty("db.driver"));
        ds.setUrl(env.getProperty("db.url"));
        ds.setUsername(env.getProperty("db.username"));
        ds.setPassword(env.getProperty("db.password"));
        ds.setMaxActive(env.getProperty("db.maxActive",Integer.class));
        ds.setInitialSize(env.getProperty("db.initialSize",Integer.class));
        return ds;

    }

    /**
     * 配置SqlSessionFactory这个工厂对象是mybatis的核心工厂对象
     * 目的是告诉mybatis找到目标数据库
     * @param dataSource
     * @return sqlSessionFactory工厂对象
     * @throws Exception
     */

    @Bean
    public SqlSessionFactory sqlSessionFactory(DataSource dataSource,
    @Value("${mybatis.mapper.location}") Resource[]  mapperLocation  )
   throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        //配置数据连接池
        bean.setDataSource(dataSource);
        bean.setMapperLocations(mapperLocation);
        return bean.getObject();
    }

}
